package com.mingyuan.library.infra.common.aop;

import com.alibaba.fastjson.JSON;
import com.mingyuan.library.infra.common.anntation.LogWriter;
import com.mingyuan.library.infra.common.enums.PrintTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 请求出入参打印切面
 * @author yangzk
 * @version V1.0
 * @date 2023/5/8
 **/
@Slf4j
@Order(1)
@Aspect
@Component
public class LogWriterAspectHandler {

    /**
     * 环绕通知
     * @author yangzk
     * @param proceedingJoinPoint
     * @param logWriter
     * @date 2023/5/8 15:48
     * @return
     **/
    @Around("@annotation(com.mingyuan.library.infra.common.anntation.LogWriter) && @annotation(logWriter)")
    public Object surroundInform(ProceedingJoinPoint proceedingJoinPoint, LogWriter logWriter) throws Throwable {
        PrintTypeEnum value = logWriter.value();
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
        String prefix = StringUtils.isBlank(logWriter.prefix()) ? methodName : logWriter.prefix();
        if (PrintTypeEnum.ALL == value || PrintTypeEnum.IN == value) {
            log.info(prefix + "开始，请求参数:{}", JSON.toJSONString(proceedingJoinPoint.getArgs()));
        }
        Object o = proceedingJoinPoint.proceed();
        if (PrintTypeEnum.ALL == value || PrintTypeEnum.OUT == value) {
            log.info(prefix + "结束，返回结果:{}", JSON.toJSONString(o));
        }
        return o;
    }
}
